import cv2


image_path = r"images/train2017/009964.jpg"
ann_path = r"labelsLJ/009964.txt"
output_image_path = 'seeit.jpg'

img = cv2.imread(image_path)

h, w, c = img.shape

with open(ann_path, mode='r', encoding='utf-8') as f:
    for line in f.readlines():
        def split_elm(*l):
            return tuple(map(float, l))
        cls, cx, cy, sw, sh = split_elm(*(line.split(' ')))

        x1 = int(w * (cx - 0.5 * sw))
        x2 = int(w * (cx + 0.5 * sw))
        y1 = int(h * (cy - 0.5 * sh))
        y2 = int(h * (cy + 0.5 * sh))

        cv2.rectangle(img, (x1, y1), (x2, y2), (255, 255, 0), 2)
    # 保存带有矩形框的图像
    cv2.imwrite(output_image_path, img)
    print(f"可视化已保存到 {output_image_path}")




# # 可视化显示
# import cv2
# import numpy as np

# def draw_yolo_boxes(image_path, annotation_path, output_path):
#     # 读取图像
#     image = cv2.imread(image_path)

#     # 获取图像的宽度和高度
#     image_width = image.shape[1]
#     image_height = image.shape[0]

#     # 读取YOLO标注信息
#     with open(annotation_path, 'r') as file:
#         lines = file.readlines()

#     # 遍历每个标注
#     for line in lines:
#         data = line.strip().split()
#         x_center, y_center, width, height, class_label = map(float, data)

#         # 将相对坐标转换为绝对坐标
#         x_center_absolute = int(x_center * image_width)
#         y_center_absolute = int(y_center * image_height)
#         width_absolute = int(width * image_width)
#         height_absolute = int(height * image_height)

#         # 计算矩形框的左上角和右下角坐标
#         x1 = int(x_center_absolute - width_absolute / 2)
#         y1 = int(y_center_absolute - height_absolute / 2)
#         x2 = int(x_center_absolute + width_absolute / 2)
#         y2 = int(y_center_absolute + height_absolute / 2)

#         # 在图像上绘制矩形框
#         color = (0, 255, 0)  # 绿色
#         thickness = 2
#         image = cv2.rectangle(image, (x1, y1), (x2, y2), color, thickness)

#         # 在矩形框上显示类别标签
#         label = f"Class {int(class_label)}"
#         font = cv2.FONT_HERSHEY_SIMPLEX
#         font_scale = 0.5
#         font_thickness = 1
#         text_size = cv2.getTextSize(label, font, font_scale, font_thickness)[0]
#         text_position = (x1, y1 - 5)
#         image = cv2.putText(image, label, text_position, font, font_scale, color, font_thickness, cv2.LINE_AA)

#     # 保存带有矩形框的图像
#     cv2.imwrite(output_path, image)
#     print(f"可视化已保存到 {output_path}")

# # 用法示例
# image_path = 'images/train2017/009964.jpg'
# annotation_path = 'labelsLJ/009964.txt'
# output_image_path = 'seeit.jpg'

# draw_yolo_boxes(image_path, annotation_path, output_image_path)